package com.lqk.fnandroid.livedata

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.lifecycle.LiveData
import androidx.room.Room
import com.lqk.fnandroid.LiveDataLocal
import com.lqk.fnandroid.databinding.ActivityLiveDataBinding
import com.lqk.fnandroid.db.UserDatabase
import kotlin.concurrent.thread

class LiveDataActivity : ComponentActivity() {

    companion object {
        private const val TAG = "LiveDataActivity"
    }

    private lateinit var binding: ActivityLiveDataBinding

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLiveDataBinding.inflate(this.layoutInflater)
        setContentView(binding.root)
        LiveDataLocal.userInfo.observe(this) {
            Log.d(TAG, "onCreate: $it")
            Log.d(TAG, "onActive: ${(LiveDataLocal.userInfo as LiveData<String>).hasObservers()}")
            Log.d(
                TAG,
                "onActive: ${(LiveDataLocal.userInfo as LiveData<String>).hasActiveObservers()}"
            )
            binding.tvData.text = "收到的值: $it"
        }

        LiveDataLocal.userInfo.observe(this, LocalObservers.userInfo)

        binding.tvData.post {
            LiveDataLocal.userInfo.value = "LiveDataActivity-2"
            thread {
                LiveDataLocal.userInfo.postValue("LiveDataActivity-3")
            }
        }
        binding.tvData.setOnClickListener {
            thread {
                val db = Room.databaseBuilder(
                    this.applicationContext,
                    UserDatabase::class.java,
                    "jetpack-db"
                ).build()
                val l = db.userDao().queryUser()
                runOnUiThread {
                    Toast.makeText(this@LiveDataActivity, "${l.size}", Toast.LENGTH_SHORT).show()
                }
            }
        }

        binding.btn.setOnClickListener {
            startActivity(Intent(this@LiveDataActivity, LiveData2Activity::class.java))
        }

    }

}